package com.cn.test.util;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * Created by Administrator on 2016/12/20.
 */

public class RecycleviewScrollBottomUtIls {


    /**
     * 当屏幕中最后一个子项lastVisibleItemPosition等于所有子项个数totalItemCount - 1，那么RecyclerView就到达了底部
     *
     * @param recyclerView
     * @return
     */

    public static boolean isVisBottom(RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        //屏幕中最后一个可见子项的position
        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
        //当前屏幕所看到的子项个数
        int visibleItemCount = layoutManager.getChildCount();
        //当前RecyclerView的所有子项个数
        int totalItemCount = layoutManager.getItemCount();
        //RecyclerView的滑动状态
        int state = recyclerView.getScrollState();
        if (visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1 && state == recyclerView.SCROLL_STATE_IDLE) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * (和 isVisBottom方式原理一样 判断方式不一样)
     * 当屏幕中最后一个子项lastVisibleItemPosition等于所有子项个数totalItemCount - 1，那么RecyclerView就到达了底部
     *
     * @param recyclerView
     * @return
     */

    public static boolean isScrollBottom(RecyclerView recyclerView) {
        //得到当前显示的最后一个item的view
        View lastChildView = recyclerView.getLayoutManager().getChildAt(recyclerView.getLayoutManager().getChildCount() - 1);
        if (lastChildView != null) {
            //得到lastChildView的bottom坐标值
            int lastChildBottom = lastChildView.getBottom();
            //得到Recyclerview的底部坐标减去底部padding值，也就是显示内容最底部的坐标
            int recyclerBottom = recyclerView.getBottom() - recyclerView.getPaddingBottom();
            //通过这个lastChildView得到这个view当前的position值
            int lastPosition = recyclerView.getLayoutManager().getPosition(lastChildView);

            //判断lastChildView的bottom值跟recyclerBottom是否相等
            //判断lastPosition是不是最后一个position
            if (lastChildBottom == recyclerBottom && lastPosition == recyclerView.getLayoutManager().getItemCount() - 1) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }


    /**
     * 这样就很清晰明了，computeVerticalScrollExtent()是当前屏幕显示的区域高度，computeVerticalScrollOffset() 是当前屏幕之前滑过的距离，而computeVerticalScrollRange()是整个View控件的高度。
     * 这种方法经过测试，暂时还没发现有bug，而且它用的是View自带的方法，所以个人觉得比较靠谱。
     *
     * @param recyclerView
     * @return
     */
    public static boolean isSlideToBottom(RecyclerView recyclerView) {
        if (recyclerView == null) return false;
        if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset()
                >= recyclerView.computeVerticalScrollRange())
            return true;
        return false;
    }


}
